import Taro from '@tarojs/taro'
import PropTypes from 'prop-types'
import { View } from '@tarojs/components'
import { AtTextarea, AtIcon } from 'taro-ui';
import { base } from '../../service/config';
import api from '../../service/api';
import '../../assets/css/iconfont.css'
import './index.less'


if (process.env.TARO_ENV === "weapp") {
  require("taro-ui/dist/weapp/css/index.css")
} else if (process.env.TARO_ENV === "h5") {
  require("taro-ui/dist/h5/css/index.css")
}

export default class WriteBox extends Taro.Component {

  constructor() {
    super(...arguments)
    this.state = {
      textValue:'',
      upImage:[],
      upServerImage:[],
      number: 1,
      sendUserId:'',
      sendQuestionCount:'',
      orderNum:'',
      writeEvenPoint:true
    }
  }

  componentDidMount = () => {

   }

   handleChange = (e) => {
    this.setState({
      textValue: e.target.value
    })
   }

   goNext = () => {
      this.setState({
        evenPoint:false
      })
      if(this.state.textValue.length < 6){
        Taro.showToast({
          title: '最少输入6个字符',
          icon:'none',
          duration: 2000
        })
        this.setState({
          evenPoint:true
        })
        return false
      }else if(this.state.evenPoint == false){
        return false
      }

      Taro.showLoading({
        title: 'loading'
      })

      let params = {}
      let that = this
      if(Taro.getStorageSync('loginInfo').role == '1'){
        params.userId = Taro.getStorageSync('loginInfo').userId
        params.doctorUserId = this.state.sendUserId
      }else{
        params.userId = this.state.sendUserId
        params.doctorUserId = Taro.getStorageSync('loginInfo').userId
      }

      params.questionCount = this.state.sendQuestionCount
      params.orderNum = this.state.orderNum
      params.role = Taro.getStorageSync('loginInfo').role
      params.content = this.state.textValue
      params.imgs = JSON.stringify(this.state.upImage)

      api.post('/inquiry/save/inquiryRecord', params).then(res=>{
        Taro.hideLoading()
        if(res.data.status == '200'){
          Taro.showToast({
            title: '发送成功',
            status:'success',
            duration: 2000
          })

          //推送微信消息
          let data = {}
          data.orderNum = res.data.data.orderNum
          data.questionCount = this.state.sendQuestionCount
          data.role = Taro.getStorageSync('loginInfo').role
          api.post('/inquiry/send/WeChatMessage',data).then(res=>{})

          setTimeout(res=>{
            that.setState({
              evenPoint:true
            })
            if(Taro.getStorageSync('loginInfo').role == 1){
              Taro.redirectTo({
                url:`/pages/UserOrder/index`
              })
            }else{
              Taro.redirectTo({
                url:`/pages/DoctorSystem/index`
              })
            }
          },1000)

        }else{
          that.setState({
            evenPoint:true
          })
          Taro.showToast({
            title: res.data.msg,
            icon:'none',
            duration: 2000
          })
        }
      })
   }

   deletImage = (index) => {
    let list = this.state.upImage
    let newList = []
    for(let i = 0;i<list.length;i++){
      if(list[i] == index){
        continue
      }
      newList.push(list[i])
    }

    this.setState({
      upImage:newList
    })
   }

   addImage = () => {
    let that = this;
    Taro.chooseImage({
      count: 6 - this.state.upImage.length,
      sizeType: ['original', 'compressed'],
      sourceType: ['album'],
      success: function (res) {
        const tempFilePaths = res.tempFilePaths
        Taro.showLoading({
          title: 'loading'
        })
        for (var i = 0; i < tempFilePaths.length; i++) {
          Taro.uploadFile({
            url: base + '/picture/upload',
            filePath: tempFilePaths[i],
            name: 'files',
            header: {
              'Content-Type': 'multipart/form-data'
            },
            success (res){
              const data = JSON.parse(res.data)
              that.state.upImage.push(data.data[0])
              Taro.hideLoading()
              that.setState({
                upImage:that.state.upImage
              })
            }
          })
        }
      }
    })
   }

  render() {
    const { upImage } = this.state
    const { sendUserId,sendQuestionCount,orderNum } = this.props

    this.setState({
      sendUserId:sendUserId,
      sendQuestionCount:sendQuestionCount,
      orderNum:orderNum
    })

    const imageList = upImage.map((item) =>{
      return <View className='at-col at-col-4 image-list-center' key={item}>
                <Image className='addUpImage' src={item}></Image>
                <View className='close' onClick={this.deletImage.bind(this,item)}>
                  <View className='icon icon-close'></View>
                </View>
             </View>
    })

    let addImage = null
    if(upImage.length < 6){
      addImage = <View className='at-col at-col-4 image-list-center'>
                  <View className='page-main-addBorder' onClick={this.addImage.bind(this)}>
                    <View className='page-main-addImage'>
                      <AtIcon prefixClass='icon' value='add' size='30' color='#bdbcbe'></AtIcon>
                      <View className='page-main-addText'>
                        上传图片
                      </View>
                    </View>
                  </View>
                </View>
    }

    return (
      <View className='page'>
        <View className='page-main'>
          <View className='page-main-textarea'>
            <AtTextarea
              value={this.state.textValue}
              onChange={this.handleChange.bind(this)}
              maxlength='500'
              minlength='6'
              height='300'
              placeholder='请描述你的年龄、性别、症状及就诊经历，便于医生进行准确分析，我们会保证你的隐私安全'
            />
          </View>

         {
           Taro.getStorageSync('loginInfo').role == 1 &&  <View className='page-main-imagelist'>
              <View className='at-row at-row--wrap'>
                {imageList}
                {addImage}
                {upImage.length == 0 &&
                  <View className='at-col at-col-8 at-col--wrap at-col__align--center'>
                    <Text className='page-main-addTips '>
                      您上传的照片仅对解答问题的医生可见，可上传6张
                    </Text>
                  </View>
                }
              </View>
            </View>
         }

          <View className='page-bottom'>
            <View className='page-bottom-btn' onClick={this.goNext.bind(this)}>
              <View>
                提交
              </View>
            </View>
          </View>
        </View>

      </View>
    )
  }
}

// WriteBox.propTypes = {
//   sendUserId: PropTypes.number
// }
